package com.visionvera.retrofitservice.utils;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Qiao on 2016/11/22.
 * 通过改变按钮的alpha值达到视觉上的按压效果
 */

public class PressEffectUtils {
    private static Handler mHandler = new Handler();

    public static View.OnTouchListener pressEffect() {
        return pressEffect(true, 100);
    }

    public static View.OnTouchListener pressEffectNoDelay() {
        return pressEffect(false, 0);
    }

    public static View.OnTouchListener pressEffect(final boolean delay, final int delayMs) {
        assert delayMs >= 0;
        return new View.OnTouchListener() {
            @Override
            public boolean onTouch(final View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        view.setAlpha(0.3f);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                view.setAlpha(1.0f);
                            }
                        }, delay ? delayMs : 0);
                        break;
                }
                return false;
            }
        };
    }
}
